const BaseController = require('../core/BaseController');

module.exports = class extends BaseController {
  constructor(props) {
    super(props);
    this.tableName = 'permission';
  }

  async select() {
    const { app, ctx } = this;
    const list = await app.mysql.select(this.tableName, {
      where: { delete_time: null }
    });
    const tree = [];
    for (let i = 0; i < list.length; i++) {
      if (list[i].pid == 0) {
        tree.push(list[i]);
      }
    }
    for (let i = 0; i < list.length; i++) {
      list[i].label = list[i].name;
      if (list[i].pid > 0) {
        for (let j = 0; j < tree.length; j++) {
          if (tree[j].id == list[i].pid) {
            if (!Array.isArray(tree[j].children)) {
              tree[j].children = [];
            }
            tree[j].children.push(list[i]);
          }
        }
      }
    }
    return tree ? ctx.success(tree) : ctx.fail();
  }

  async updateByIds() {
    const { ctx, app } = this;
    const { ids, user_id } = ctx.request.body;
    let rs = await app.mysql.beginTransactionScope(async conn => {
      try {
        await conn.delete('user_permission', { user_id });
        if(!Array.isArray(ids)){
          ids = JSON.parse(ids);
        }
        for (let i = 0; i < ids.length; i++) {
          await conn.insert('user_permission', { permission_id: ids[i], user_id });
        }
        return true;
      } catch (error) {
        return false;
      }
      
    });
    return rs ? ctx.success() : ctx.fail('更新权限失败');
  }

}

